// 添加日志功能
const logger = {
    async shouldLog() {
        const { enableLogging = true } = await chrome.storage.sync.get('enableLogging');
        return enableLogging;
    },
    async debug(message, ...args) {
        if (await this.shouldLog()) {
            console.log(`[Form Persistence Popup] ${message}`, ...args);
        }
    },
    async info(message, ...args) {
        if (await this.shouldLog()) {
            console.info(`[Form Persistence Popup] ${message}`, ...args);
        }
    },
    async warn(message, ...args) {
        if (await this.shouldLog()) {
            console.warn(`[Form Persistence Popup] ${message}`, ...args);
        }
    },
    async error(message, ...args) {
        if (await this.shouldLog()) {
            console.error(`[Form Persistence Popup] ${message}`, ...args);
        }
    }
};

// 将字段 ID 转换为友好的显示名称
async function getDisplayFieldName(fieldName) {
    // 如果字段名是自动生成的 (例如: text_form0_1_username)
    const autoGenPattern = /^(\w+)_form(\d+|standalone)_(\d+)(?:_(.+)?)?$/;
    const match = fieldName.match(autoGenPattern);

    if (match) {
        const [, elementType, formIndex, index, hint] = match;
        // 如果有提示文本(来自 label 或 placeholder)，优先使用
        if (hint) {
            return hint.replace(/([A-Z])/g, ' $1')
                .replace(/^./, str => str.toUpperCase())
                .trim();
        }

        // 获取元素类型的翻译文本
        const typeMessage = await getMessage(`inputType_${elementType}`);
        const fieldMessage = await getMessage('inputField_number', [index]);

        // 如果有元素类型的翻译，将其与序号组合
        if (typeMessage) {
            return `${typeMessage} ${index}`;
        }

        return fieldMessage;
    }

    // 如果字段名看起来是有意义的 ID 或 name，美化显示
    return fieldName
        .replace(/[_-]/g, ' ') // 替换下划线和连字符为空格
        .replace(/([A-Z])/g, ' $1') // 在大写字母前添加空格
        .replace(/^./, str => str.toUpperCase()) // 首字母大写
        .trim(); // 移除多余空格
}

// 页面状态检查函数优化
async function checkCurrentPageStatus() {
    const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
    const currentUrl = tabs[0].url;
    const { enabledUrls = [] } = await chrome.storage.sync.get('enabledUrls');

    const isEnabled = enabledUrls.some(pattern => {
        // 如果模式中没有通配符，进行精确匹配
        if (!pattern.includes('*')) {
            return currentUrl === pattern;
        }

        // 否则使用通配符匹配
        const regexPattern = pattern
            .replace(/\./g, '\\.')
            .replace(/\*/g, '.*')
            .replace(/\//g, '\\/');
        const regex = new RegExp(regexPattern);
        return regex.test(currentUrl);
    });

    // 更新状态显示
    updateStatusDisplay(isEnabled);
}

// 更新页面状态显示
function updateStatusDisplay(isEnabled) {
    const statusElement = document.getElementById('currentStatus');
    if (!statusElement) return;

    statusElement.textContent = getMessage(isEnabled ? 'enabled' : 'disabled');
    statusElement.className = `font-medium ${isEnabled ? 'enabled' : 'disabled'}`;

    // 更新启用/禁用按钮文本
    const toggleButton = document.getElementById('toggleCurrentPage');
    if (toggleButton) {
        toggleButton.textContent = getMessage(isEnabled ? 'disable' : 'enable');
    }
}

// 切换当前页面启用状态
async function toggleCurrentPage() {
    try {
        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
        const url = tab.url;
        const { enabledUrls = [], disabledUrls = [] } = await chrome.storage.sync.get(['enabledUrls', 'disabledUrls']);

        // 检查当前状态
        let matchedPattern = null;
        const isEnabled = enabledUrls.some(pattern => {
            if (isUrlMatched(url, pattern)) {
                matchedPattern = pattern;
                return true;
            }
            return false;
        });

        let newEnabledUrls = [...enabledUrls];
        let newDisabledUrls = [...disabledUrls];

        if (isEnabled) {
            // 从启用列表移到禁用列表，使用原有的匹配模式
            newEnabledUrls = enabledUrls.filter(pattern => pattern !== matchedPattern);
            if (!disabledUrls.includes(matchedPattern)) {
                newDisabledUrls.push(matchedPattern);
            }

            try {
                await chrome.tabs.sendMessage(tab.id, { action: 'stopSaving' });
            } catch (error) {
                logger.warn('发送停止保存消息失败，可能需要刷新页面', error);
            }

            showNotification('已禁用当前网页', 'warning');
        } else {
            // 从禁用列表移到启用列表
            const matchedDisabledPattern = disabledUrls.find(pattern => isUrlMatched(url, pattern));
            newDisabledUrls = disabledUrls.filter(pattern => pattern !== matchedDisabledPattern);

            // 如果找到匹配的禁用模式，使用它；否则使用域名作为模式
            const patternToAdd = matchedDisabledPattern || new URL(url).hostname;
            if (!enabledUrls.includes(patternToAdd)) {
                newEnabledUrls.push(patternToAdd);
            }

            try {
                await chrome.tabs.sendMessage(tab.id, { action: 'reinitialize' });
            } catch (error) {
                logger.warn('发送重新初始化消息失败，可能需要刷新页面', error);
            }

            showNotification('已启用当前网页', 'success');
        }

        // 保存更新后的列表
        await chrome.storage.sync.set({
            enabledUrls: newEnabledUrls,
            disabledUrls: newDisabledUrls
        });

        // 更新状态显示
        updatePageStatus();

    } catch (error) {
        logger.error('切换页面状态失败:', error);
        showNotification('操作失败，请重试', 'error');
    }
}

// 创建表单字段编辑界面
async function createFormFieldEditor(fieldName, value, type) {
    const fieldDiv = document.createElement('div');
    fieldDiv.className = 'form-field bg-white p-3 rounded-lg shadow-sm mb-2';

    const nameDiv = document.createElement('div');
    nameDiv.className = 'field-name text-sm text-gray-600 mb-1';
    nameDiv.textContent = await getDisplayFieldName(fieldName);

    const valueDiv = document.createElement('div');
    valueDiv.className = 'field-value';

    const input = document.createElement('input');
    input.type = type;
    input.className = type === 'checkbox'
        ? 'rounded text-blue-500 focus:ring-blue-500'
        : 'w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500';

    if (type === 'checkbox') {
        input.checked = value;
    } else {
        input.value = value || '';
    }
    input.dataset.fieldName = fieldName;

    valueDiv.appendChild(input);
    fieldDiv.appendChild(nameDiv);
    fieldDiv.appendChild(valueDiv);

    return fieldDiv;
}



// 保存编辑后的表单数据
async function saveFormData(url, formContainer) {
    const formData = {};
    const forms = formContainer.querySelectorAll('h5');

    forms.forEach((form, formIndex) => {
        formData[formIndex] = {};
        let currentNode = form.nextElementSibling;

        while (currentNode && currentNode.className === 'form-field') {
            const input = currentNode.querySelector('input');
            if (input) {
                const fieldName = input.dataset.fieldName;
                const value = input.type === 'checkbox' ? input.checked : input.value;
                formData[formIndex][fieldName] = value;
            }
            currentNode = currentNode.nextElementSibling;
        }
    });

    // 添加最后修改时间
    const savedData = {
        data: formData,
        lastModified: Date.now()
    };

    await chrome.storage.local.set({ [url]: savedData });
    formContainer.style.display = 'none';
    await loadSavedFormData(); // 重新加载数据列表
}

// 加载所有保存的表单数据
async function loadSavedFormData() {
    const savedDataContainer = document.getElementById('savedData');
    if (!savedDataContainer) {
        logger.error('找不到数据容器元素');
        return;
    }

    try {
        // 显示加载状态
        savedDataContainer.innerHTML = '<div class="text-gray-500 text-center py-3">正在加载数据...</div>';

        // 获取所有保存的数据
        const result = await chrome.storage.local.get(null);
        const urls = Object.keys(result);

        if (urls.length === 0) {
            savedDataContainer.innerHTML = '<div class="text-gray-500 text-center py-3">没有保存的表单数据</div>';
            return;
        }

        // 清空容器
        savedDataContainer.innerHTML = '';

        // 按最后修改时间排序
        urls.sort((a, b) => {
            return (result[b].lastModified || 0) - (result[a].lastModified || 0);
        });

        // 创建数据项
        for (const url of urls) {
            try {
                const savedData = result[url];
                if (!savedData || !savedData.data) continue;

                const urlItem = document.createElement('div');
                urlItem.className = 'url-item bg-white p-4 rounded-lg shadow-sm mb-4 hover:shadow-md transition-shadow';

                const urlText = document.createElement('div');
                urlText.className = 'url-text text-gray-700 mb-2 break-all';
                urlText.textContent = url;

                const timeText = document.createElement('div');
                timeText.className = 'text-xs text-gray-500 mb-2';
                timeText.textContent = savedData.lastModified ?
                    `最后更新: ${new Date(savedData.lastModified).toLocaleString('zh-CN')}` :
                    '更新时间未知';

                const buttonsDiv = document.createElement('div');
                buttonsDiv.className = 'flex space-x-2 mt-2';

                const editButton = document.createElement('button');
                editButton.className = 'flex-1 px-3 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-lg transition-colors text-sm';
                editButton.textContent = '编辑';
                editButton.onclick = () => {
                    document.querySelectorAll('.form-data').forEach(form => {
                        form.style.display = 'none';
                    });

                    let formContainer = document.getElementById(`form-${url}`);
                    if (!formContainer) {
                        formContainer = createEditForm(url, savedData);
                        urlItem.appendChild(formContainer);
                    }
                    formContainer.style.display = 'block';
                };

                const deleteButton = document.createElement('button');
                deleteButton.className = 'flex-1 px-3 py-2 bg-red-500 hover:bg-red-600 text-white rounded-lg transition-colors text-sm';
                deleteButton.textContent = '删除';
                deleteButton.onclick = () => deleteFormData(url);

                buttonsDiv.appendChild(editButton);
                buttonsDiv.appendChild(deleteButton);

                urlItem.appendChild(urlText);
                urlItem.appendChild(timeText);
                urlItem.appendChild(buttonsDiv);
                savedDataContainer.appendChild(urlItem);
            } catch (error) {
                logger.error(`处理URL数据失败: ${url}`, error);
                continue;
            }
        }
    } catch (error) {
        logger.error('加载数据失败:', error);
        savedDataContainer.innerHTML = '<div class="text-red-500 text-center py-3">加载数据失败，请重试</div>';
    }
}

// 删除特定 URL 的表单数据
async function deleteFormData(url) {
    if (!confirm('确定要删除这个页面的表单数据吗？此操作无法撤销。')) {
        return;
    }

    // 获取当前标签页
    const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
    const currentTab = tabs[0];

    // 如果删除的是当前页面的数据，发送停止保存消息
    if (url === currentTab.url) {
        try {
            await chrome.tabs.sendMessage(currentTab.id, { action: 'stopSaving' });
            logger.info('已发送停止保存数据的指令');
        } catch (error) {
            logger.error('发送停止保存指令失败:', error);
        }
    }

    await chrome.storage.local.remove(url);
    loadSavedFormData(); // 重新加载列表
}

// 删除所有保存的表单数据
async function deleteAllFormData() {
    const confirmMessage = await getMessage('confirmDeleteAll');
    if (!confirm(confirmMessage)) {
        return;
    }

    const confirmAgainMessage = await getMessage('confirmDeleteAllAgain');
    if (!confirm(confirmAgainMessage)) {
        return;
    }

    // 获取当前标签页并发送停止保存消息
    const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
    const currentTab = tabs[0];

    try {
        await chrome.tabs.sendMessage(currentTab.id, { action: 'stopSaving' });
        logger.info('已发送停止保存数据的指令');
    } catch (error) {
        logger.error('发送停止保存指令失败:', error);
    }

    await chrome.storage.local.clear();
    showNotification('deleteSuccess', 'success');
    loadSavedFormData(); // 重新加载列表
}

// 打开选项页面
function openOptionsPage() {
    chrome.runtime.openOptionsPage();
}

// 获取当前激活的标签页
async function getCurrentTab() {
    const [tab] = await chrome.tabs.query({
        active: true,
        currentWindow: true
    });
    return tab;
}

// 显示加载状态
function showLoading(element, text = '加载中...') {
    element.innerHTML = `
        <div class="flex items-center justify-center py-4">
            <div class="animate-spin mr-2">
                <svg class="w-5 h-5 text-gray-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
            </div>
            <span class="text-gray-500">${text}</span>
        </div>
    `;
}

// 显示当前页面状态
async function updatePageStatus() {
    const statusElement = document.getElementById('currentStatus');
    const toggleButton = document.getElementById('toggleCurrentPage');
    const urlButton = document.getElementById('toggleUrlButton');
    const tab = await getCurrentTab();

    if (!tab || !statusElement || !toggleButton || !urlButton) {
        return;
    }

    showLoading(statusElement, await getMessage('checking'));

    try {
        const { enabledUrls = [], disabledUrls = [] } = await chrome.storage.sync.get(['enabledUrls', 'disabledUrls']);
        logger.debug('检查URL权限:', {
            currentUrl: tab.url,
            enabledUrls,
            disabledUrls
        });

        let isEnabled = false;
        let isDisabled = false;

        // 改进URL匹配逻辑
        for (const pattern of enabledUrls) {
            if (isUrlMatched(tab.url, pattern)) {
                isEnabled = true;
                break;
            }
        }

        for (const pattern of disabledUrls) {
            if (isUrlMatched(tab.url, pattern)) {
                isDisabled = true;
                break;
            }
        }

        const isAdded = isEnabled || isDisabled;

        // 更新状态显示
        statusElement.textContent = await getMessage(isEnabled ? 'enabled' : 'disabled');
        statusElement.className = `text-white px-2 py-1 rounded ${isEnabled ? '#16a34a' : '#4b5563'}`;
        statusElement.style.backgroundColor = isEnabled ? '#16a34a' : '#4b5563';

        // 更新启用/禁用按钮
        toggleButton.textContent = await getMessage(isEnabled ? 'disable' : 'enable');
        toggleButton.className = `grid-button ${isEnabled ? 'warning-button' : 'success-button'}`;
        toggleButton.disabled = !isAdded;

        // 更新添加/删除按钮
        urlButton.textContent = await getMessage(isAdded ? 'remove' : 'add');
        urlButton.className = `grid-button ${isAdded ? 'danger-button' : 'primary-button'}`;

        logger.debug('页面状态更新:', { isEnabled, isDisabled, isAdded });
    } catch (error) {
        statusElement.textContent = await getMessage('checkingError');
        logger.error('检查页面状态失败:', error);
    }
}

// 添加精确的URL匹配函数
function isUrlMatched(url, pattern) {

    // 完整URL匹配
    return url.includes(pattern);
}

// 显示保存的表单数据
async function displaySavedData() {
    const savedDataElement = document.getElementById('savedData');
    const tab = await getCurrentTab();

    if (!tab) {
        savedDataElement.innerHTML = `<div class="text-gray-500 text-center py-3">${await getMessage('cannotGetPageInfo')}</div>`;
        return;
    }

    showLoading(savedDataElement);

    try {
        const result = await chrome.storage.local.get(tab.url);
        const savedData = result[tab.url];

        if (!savedData || !savedData.data) {
            savedDataElement.innerHTML = `<div class="text-gray-500 text-center py-3">${await getMessage('noSavedData')}</div>`;
            return;
        }

        const formattedDate = new Date(savedData.lastModified).toLocaleString();
        let html = '';

        const formData = savedData.data;

        for (const [formIndex, fields] of Object.entries(formData)) {
            html += `<div class="saved-form bg-white p-4 rounded-lg shadow-sm mb-4 hover:shadow-md transition-shadow">`;
            // 使用getMessage获取表单标题
            const formTitle = formIndex === 'standalone_inputs'
                ? await getMessage('standaloneFormFields')
                : await getMessage('formNumber', [parseInt(formIndex.replace('form_', '')) + 1]);
            html += `<div class="form-header text-gray-700 font-medium pb-2 mb-3 border-b">${formTitle}</div>`;

            // 异步处理每个字段
            for (const [name, value] of Object.entries(fields)) {
                const displayName = await getDisplayFieldName(name);
                html += `
                    <div class="field-item bg-gray-50 p-3 rounded-lg hover:bg-gray-100 transition-colors">
                        <div class="field-name text-sm text-gray-500 mb-1">${displayName}</div>
                        <div class="field-value text-gray-700 break-words">${value}</div>
                    </div>
                `;
            }

            html += `</div>`;
        }

        html += `
            <div class="text-xs text-gray-500 mt-4 text-center">
                ${await getMessage('lastModified', [formattedDate])}
            </div>
        `;

        savedDataElement.innerHTML = html;
        
        // 添加保存数据集按钮
        const saveDatasetBtn = document.createElement('button');
        saveDatasetBtn.className = 'w-full px-4 py-2 mb-4 bg-blue-500 hover:bg-blue-600 text-white rounded-lg transition-colors text-sm';
        saveDatasetBtn.textContent = '保存为数据集';
        saveDatasetBtn.onclick = saveAsDataset;
        savedDataElement.appendChild(saveDatasetBtn);


    } catch (error) {
        logger.error('加载数据失败:', error);
        savedDataElement.innerHTML = `<div class="text-red-500 text-center py-3">${await getMessage('loadingError')}</div>`;
    }
}

// 删除所有保存的数据
async function deleteData() {
    const confirmMessage = await getMessage('confirmDelete');
    if (!confirm(confirmMessage)) {
        return;
    }
    const tab = await getCurrentTab();
    if (!tab) return;

    try {
        await chrome.storage.local.remove(tab.url);
        showNotification('deleteSuccess', 'success');
        displaySavedData(); // 刷新显示
    } catch (error) {
        logger.error('删除数据失败:', error);
        showNotification('deleteError', 'error');
    }
}

// 添加当前网页到启用列表
async function addCurrentPage() {
    try {
        const tab = await getCurrentTab();
        if (!tab) return;

        const { enabledUrls = [] } = await chrome.storage.sync.get('enabledUrls');
        const urlPattern = new URL(tab.url).pathname;

        if (!enabledUrls.includes(urlPattern)) {
            enabledUrls.push(urlPattern);
            await chrome.storage.sync.set({ enabledUrls });
        }

        // 通知内容脚本重新初始化
        try {
            await chrome.tabs.sendMessage(tab.id, { action: 'reinitialize' });
        } catch (error) {
            logger.warn('发送重新初始化消息失败，可能需要刷新页面', error);
        }

        showNotification('pageAdded', 'success');
    } catch (error) {
        logger.error('添加当前网页失败:', error);
        showNotification('operationFailed', 'error');
    }
}

// 禁用当前网页
async function disableCurrentPage() {
    try {
        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
        const url = tab.url;

        const { enabledUrls = [] } = await chrome.storage.sync.get('enabledUrls');

        // 从启用列表中移除当前URL
        const newEnabledUrls = enabledUrls.filter(pattern => pattern !== url);
        await chrome.storage.sync.set({ enabledUrls: newEnabledUrls });

        // 更新状态显示
        updateStatusDisplay(false);

        // 通知内容脚本停止保存
        try {
            await chrome.tabs.sendMessage(tab.id, { action: 'stopSaving' });
        } catch (error) {
            logger.warn('发送停止保存消息失败，可能需要刷新页面', error);
        }

        showNotification('pageDisabled', 'warning');
    } catch (error) {
        logger.error('禁用当前网页失败:', error);
        showNotification('operationFailed', 'error');
    }
}

// 删除当前网页
async function removeCurrentPage() {
    const confirmMessage = await getMessage('confirmRemovePage');
    if (!confirm(confirmMessage)) {
        return;
    }

    try {
        const tab = await getCurrentTab();
        if (!tab) return;

        const { enabledUrls = [] } = await chrome.storage.sync.get('enabledUrls');
        const urlPattern = new URL(tab.url).pathname;

        const index = enabledUrls.indexOf(urlPattern);
        if (index > -1) {
            enabledUrls.splice(index, 1);
            await chrome.storage.sync.set({ enabledUrls });

            // 同时删除保存的数据
            await chrome.storage.local.remove(tab.url);
        }

        // 通知内容脚本停止监听
        try {
            await chrome.tabs.sendMessage(tab.id, { action: 'stopSaving' });
        } catch (error) {
            logger.warn('发送停止保存消息失败，可能需要刷新页面', error);
        }

        showNotification('pageDeleted', 'success');
    } catch (error) {
        logger.error('删除当前网页失败:', error);
        showNotification('operationFailed', 'error');
    }
}

// 显示通知
function showNotification(messageKey, type = 'info') {
    const notification = document.getElementById('notification');
    getMessage(messageKey).then(text => {
        notification.textContent = text;
        notification.className = `notification ${type}`;

        // 自动隐藏通知
        setTimeout(() => {
            notification.classList.add('hidden');
        }, 3000);
    });
}

// 切换网址按钮（添加/删除）
async function toggleUrl() {
    try {
        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
        const url = tab.url;
        const { enabledUrls = [], disabledUrls = [] } = await chrome.storage.sync.get(['enabledUrls', 'disabledUrls']);

        // 检查URL在启用列表还是禁用列表中
        const isEnabled = enabledUrls.some(pattern => isUrlMatched(url, pattern));
        const isDisabled = disabledUrls.some(pattern => isUrlMatched(url, pattern));
        const isAdded = isEnabled || isDisabled;

        if (isAdded) {
            // 删除操作
            if (!confirm('确定要删除当前网页吗？这将删除该页面的所有表单数据和设置。')) {
                return;
            }

            // 从启用和禁用列表中都移除
            const newEnabledUrls = enabledUrls.filter(pattern => !isUrlMatched(url, pattern));
            const newDisabledUrls = disabledUrls.filter(pattern => !isUrlMatched(url, pattern));

            await chrome.storage.sync.set({
                enabledUrls: newEnabledUrls,
                disabledUrls: newDisabledUrls
            });
            await chrome.storage.local.remove(url);

            try {
                await chrome.tabs.sendMessage(tab.id, { action: 'stopSaving' });
            } catch (error) {
                logger.warn('发送停止保存消息失败，可能需要刷新页面', error);
            }

            showNotification('已删除当前网页', 'success');
        } else {
            // 添加操作（默认添加到启用列表）
            enabledUrls.push(url);
            await chrome.storage.sync.set({ enabledUrls });

            try {
                await chrome.tabs.sendMessage(tab.id, { action: 'reinitialize' });
            } catch (error) {
                logger.warn('发送重新初始化消息失败，可能需要刷新页面', error);
            }

            showNotification('已添加当前网页', 'success');
        }

        // 更新页面状态
        updatePageStatus();
        displaySavedData();
    } catch (error) {
        logger.error('操作失败:', error);
        showNotification('操作失败，请重试', 'error');
    }
}

// 添加更新数据的函数
async function refreshData() {
    // 找到刷新按钮
    const refreshButton = document.getElementById('refreshData');
    if (refreshButton) {
        // 给 SVG 添加旋转动画，而不是给整个按钮
        const svg = refreshButton.querySelector('svg');
        if (svg) {
            svg.classList.add('animate-spin');
        }
    }

    try {
        // 重新加载状态和数据
        await Promise.all([
            updatePageStatus(),
            displaySavedData()
        ]);

        // 显示成功提示
        showNotification('dataRefreshed', 'success');
    } catch (error) {
        logger.error('刷新数据失败:', error);
        showNotification('更新失败，请重试', 'error');
    } finally {
        if (refreshButton) {
            const svg = refreshButton.querySelector('svg');
            if (svg) {
                svg.classList.remove('animate-spin');
            }
        }
    }
}

// 本地化消息管理系统
const i18nMessageCache = {
    zh_CN: null,
    en: null
};

// 加载指定语言的消息
async function loadMessages(locale) {
    // 先从预加载缓存中获取
    const cacheKey = `i18n_${locale}`;
    try {
        const cache = await chrome.storage.local.get(cacheKey);
        if (cache[cacheKey] && cache[cacheKey].messages) {
            logger.debug('从预加载缓存加载语言消息:', locale);
            return cache[cacheKey].messages;
        }
    } catch (error) {
        logger.error('加载缓存的语言消息失败:', error);
    }

    // 如果缓存中没有，则从文件加载
    try {
        const response = await fetch(chrome.runtime.getURL(`_locales/${locale}/messages.json`));
        const messages = await response.json();
        return messages;
    } catch (error) {
        logger.error('加载语言消息失败:', error);
        // 如果加载失败且不是默认语言，尝试回退到默认语言
        if (locale !== 'zh_CN') {
            logger.warn(`加载语言 ${locale} 失败，回退到默认语言`);
            return loadMessages('zh_CN');
        }
        return null;
    }
}

// 获取指定语言的消息
async function getMessageFromLocale(key, locale, substitutions = null) {
    const messages = await loadMessages(locale);
    if (!messages || !messages[key]) {
        return key;
    }

    let message = messages[key].message;

    // 处理替换参数
    if (substitutions && messages[key].placeholders) {
        Object.entries(messages[key].placeholders).forEach(([placeholder, config]) => {
            const index = parseInt(config.content.replace('$', '')) - 1;
            if (substitutions[index]) {
                message = message.replace(`$${placeholder.toUpperCase()}$`, substitutions[index]);
            }
        });
    }

    return message;
}

// 更新获取消息的函数
async function getMessage(key, substitutions = null) {
    const { language = 'zh_CN' } = await chrome.storage.sync.get('language');
    return await getMessageFromLocale(key, language, substitutions);
}

// 更新页面上的所有i18n文本
async function updateI18nText() {
    const elements = document.querySelectorAll('[data-i18n]');
    for (const element of elements) {
        const key = element.getAttribute('data-i18n');
        const text = await getMessage(key);
        if (text) {
            if (element.tagName.toLowerCase() === 'input' && element.type === 'text') {
                element.placeholder = text;
            } else {
                element.textContent = text;
            }
        }
    }

    // 更新带title属性的元素
    const titleElements = document.querySelectorAll('[data-i18n-title]');
    for (const element of titleElements) {
        const key = element.getAttribute('data-i18n-title');
        const text = await getMessage(key);
        if (text) {
            element.title = text;
        }
    }
}

// 加载语言设置
async function loadLanguageSettings() {
    try {
        const { language = 'zh_CN' } = await chrome.storage.sync.get('language');
        document.getElementById('languageSelect').value = language;
    } catch (error) {
        logger.error('加载语言设置失败:', error);
    }
}

// 保存语言设置
async function saveLanguageSettings(newLanguage) {
    try {
        await chrome.storage.sync.set({ language: newLanguage });

        // 通知所有打开的标签页更新语言
        const tabs = await chrome.tabs.query({});
        for (const tab of tabs) {
            try {
                await chrome.tabs.sendMessage(tab.id, {
                    action: 'updateLanguage',
                    language: newLanguage
                });
            } catch (error) {
                // 忽略未加载内容脚本的标签页错误
            }
        }

        // 通知后台脚本
        chrome.runtime.sendMessage({
            action: 'updateLanguage',
            language: newLanguage
        });

        // 通知所有其他扩展页面
        chrome.runtime.sendMessage({
            action: 'updateLanguage',
            language: newLanguage,
            source: 'popup'
        });

        // 显示成功提示
        showNotification(getMessage('languageChangeRestart'), 'success');

        // 重新加载弹窗和选项页
        setTimeout(async () => {
            // 重新加载当前弹窗
            window.location.reload();

            // 尝试重新加载选项页
            try {
                const optionsTab = await chrome.tabs.query({ url: chrome.runtime.getURL('options.html') });
                if (optionsTab.length > 0) {
                    await chrome.tabs.reload(optionsTab[0].id);
                }
            } catch (error) {
                logger.warn('重新加载选项页失败:', error);
            }
        }, 500);
    } catch (error) {
        logger.error('保存语言设置失败:', error);
        showNotification(getMessage('settingsSaveError'), 'error');
    }
}

// 保存为数据集
async function saveAsDataset() {
    try {
        const tab = await getCurrentTab();
        if (!tab) {
            showNotification('无法获取当前页面信息', 'error');
            return;
        }

        const result = await chrome.storage.local.get(tab.url);
        const savedData = result[tab.url];

        if (!savedData || !savedData.data) {
            showNotification('当前页面没有可保存的数据', 'warning');
            return;
        }

        // 提示用户输入数据集名称
        const datasetName = prompt('请输入数据集名称：');
        if (!datasetName) return;

        // 获取现有数据集
        const { datasets = [] } = await chrome.storage.sync.get('datasets');

        // 如果数据集已存在，确认是否覆盖
        if (datasets[datasetName]) {
            if (!confirm(`数据集 "${datasetName}" 已存在，是否覆盖？`)) {
                return;
            }
        }

        // 创建新的数据集对象
        const newDataset = {
            name: datasetName,
            url: tab.url,
            data: savedData.data,
            createTime: Date.now(),
            disabled: true // 默认禁用,
        };

        // 添加到数据集列表
        datasets.push(newDataset);

        // 保存到 sync 存储
        await chrome.storage.sync.set({ datasets });

        showNotification('数据集保存成功', 'success');

    } catch (error) {
        logger.error('保存数据集失败:', error);
        showNotification('保存数据集失败', 'error');
    }
}

// 初始化
document.addEventListener('DOMContentLoaded', async () => {
    // 初始化国际化文本
    await updateI18nText();

    // 立即检查当前页面状态
    await updatePageStatus();

    // 加载已保存的表单数据
    await displaySavedData();

    // 绑定按钮事件
    document.getElementById('deleteData')?.addEventListener('click', deleteData);
    document.getElementById('openSettings')?.addEventListener('click', () => chrome.runtime.openOptionsPage());
    document.getElementById('toggleUrlButton')?.addEventListener('click', toggleUrl);
    document.getElementById('toggleCurrentPage')?.addEventListener('click', toggleCurrentPage);
    document.getElementById('removeCurrentPage')?.addEventListener('click', removeCurrentPage);

    // 添加刷新按钮事件监听
    document.getElementById('refreshData')?.addEventListener('click', refreshData);

    // 加载语言设置
    await loadLanguageSettings();

    // 绑定语言切换事件
    document.getElementById('languageSelect')?.addEventListener('change', event => {
        const newLanguage = event.target.value;
        saveLanguageSettings(newLanguage);
    });
});

// 监听语言更改消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.action === 'updateLanguage') {
        // 如果消息来源是popup并且当前也是popup页面，忽略它以避免重复刷新
        if (message.source === 'popup' && window.location.pathname.endsWith('popup.html')) {
            return;
        }

        // 重新加载所有国际化文本
        updateI18nText();
        // 刷新显示的数据
        displaySavedData();
        sendResponse({ success: true });
    }
});